import MySQLdb
from types import *

class DB:
    def __init__(self):
        self.conn = MySQLdb.connect (host = "localhost",
                                   user = "root",
                                   passwd = "",
                                   db = "testy")
        self.cursor = self.conn.cursor()

    def __del__(self):
        self.cursor.close()
        self.conn.close()

    def quote(self,value):
        if type(value) is StringType:
            return '\''+value+'\''
        return str(value)


    def version(self):
        c = self.cursor
        c.execute ("SELECT VERSION()")
        row = c.fetchone ()
        print "server version:", row[0]

    def create_table(self,table,fields):
        c = self.cursor
        fields_list = [name+' '+fields[name] for name in fields.keys()]
        sql = 'CREATE TABLE ' + table + '(id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,'+', '.join(fields_list)+')'
        c.execute ('DROP TABLE IF EXISTS ' + table + '')
        c.execute (sql)

    def insert(self,table,fields):
        c = self.cursor
        fields_list = [name+'='+self.quote(fields[name]) for name in fields.keys()]
        sql ='INSERT ' + table + ' SET '+', '.join(fields_list)
        c.execute (sql)

    def select(self, table, fields, conditions):
        c = self.cursor
        c.execute ('SELECT ' + ','.join(fields)+ ' FROM ' + table + ' WHERE ' + ' '.join(conditions))
        rows = c.fetchall ()
        return rows

    def select_plain(self,sql):
        self.cursor.execute('SELECT '+sql)
        rows = self.cursor.fetchall()
        return rows
